package com.edu.labmanager.controller;


import com.edu.labmanager.common.MyUserDetails;
import com.edu.labmanager.domain.VO.EmailVo;
import com.edu.labmanager.entity.Email;
import com.edu.labmanager.service.IEmailService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;

import java.util.List;

@Controller
@Slf4j
@RequestMapping("/email")
public class EmailController {
    @Autowired
    private IEmailService emailService;
    @GetMapping("")
    public String select(Model model, Authentication authentication){
        MyUserDetails userDetails = (MyUserDetails) authentication.getPrincipal();
        Long id = Long.valueOf(userDetails.getId());
        List<Email> emails = emailService.query().eq("user_id", id).list();
        model.addAttribute("emails",emails);
        return "email";
    }
    @GetMapping("delete/{id}")
    public String delete(@PathVariable Long id){
        emailService.removeById(id);
        return "redirect:/email";
    }
    @GetMapping("select/{id}")
    public String select(@PathVariable Long id, Model model,Authentication authentication){
        Email email = emailService.getById(id);
        MyUserDetails myUserDetails = (MyUserDetails) authentication.getPrincipal();
        String username = myUserDetails.getUsername();
        EmailVo emailVo = new EmailVo();
        BeanUtils.copyProperties(email,emailVo);
        emailVo.setUsername(username);
        model.addAttribute("email",emailVo);
        return "email-info";
    }

}
